package com.as3extensions
{
  import com.as3extensions.helpers.*;
  
  public class Template
  {
    private var _template : String;
    private var _pattern : RegExp;
    
    public function Template( template : String, pattern : RegExp = null)
    {
      this._template = template || '';
      this._pattern = pattern || new RegExp(/(^|.|\r|\n)(#\{(.*?)\})/);
    }
    
    public function evaluate( object : Object ) : String
    {
      return StringHelper.gsub( _template, _pattern, function( match : Array ) : String 
      {
        if (object == null) return '';
        
        var before : String = match[1] || '';
        if (before == '\\') return match[2];

        var ctx : Object = object;
        var expr : String = match[3];
        var pattern : RegExp = new RegExp(/^([^.[]+|\[((?:.*?[^\\])?)\])(\.|\[|$)/)
        match = pattern.exec(expr);
        
        if (match == null) return '';

        while (match != null) {
          var comp : String = StringHelper.startsWith(match[1], '[') ? StringHelper.gsub(match[2], new RegExp('\\\\]'), ']') : match[1];
          
          ctx = ctx[comp];
          
          if (null == ctx || '' == match[3]) break;
          expr = expr.substring('[' == match[3] ? match[1].length : match[0].length);
          match = pattern.exec(expr);
        }

        return before + StringHelper.interpret(ctx);
      });
    }
  }
}